import os.path

try:
    import azure.cognitiveservices.speech as speechsdk
except ImportError:
    print("""
    Importing the Speech SDK for Python failed.
    Refer to
    https://docs.microsoft.com/azure/cognitive-services/speech-service/quickstart-text-to-speech-python for
    installation instructions.
    """)
    import sys
    sys.exit(1)


# Set up the subscription info for the Speech Service:
# Replace with your own subscription key and service region (e.g., "westus").
# speech_key, service_region = "e8ad8cf4515348b7a7b68d7241bf41db", "eastus"
speech_key, service_region = "eb51c16bbc854c3687530bf04e7fbf0c", "japaneast"

def text_to_mp3(text: str) -> None:
    """
    使用Azure的Speech SDK将文本转换为MP3文件
    text: 要转换的文本

    """

    speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
    language = "zh-CN"
    speech_config.speech_synthesis_language = language
    voice = "Microsoft Server Speech Text to Speech Voice (zh-CN, XiaoshuangNeural)"
    speech_config.speech_synthesis_voice_name = voice
    speech_config.set_speech_synthesis_output_format(speechsdk.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3)

    file_name = "text_output.mp3"
    # file_name = dirname(dirname(abspath(__file__))) + r'\static\audio\outputaudio.mp3'
    file_config = speechsdk.audio.AudioOutputConfig(filename=file_name)

    speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=file_config)

    result = speech_synthesizer.speak_text_async(text).get()

    # Check result
    if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
        print("Speech synthesized for text [{}], and the audio was saved to [{}]".format(text, file_name))
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print("Speech synthesis canceled: {}".format(cancellation_details.reason))
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print("Error details: {}".format(cancellation_details.error_details))

from os.path import abspath, dirname
def text_to_mp3_ssml() -> None:
    """
    使用Azure的Speech SDK将文本转换为MP3文件
    使用SSML格式，可以添加语调感情等

    """

    speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
    language = "zh-CN"
    speech_config.speech_synthesis_language = language
    voice = "Microsoft Server Speech Text to Speech Voice (zh-CN, XiaoshuangNeural)"
    speech_config.speech_synthesis_voice_name = voice
    speech_config.set_speech_synthesis_output_format(speechsdk.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3)

    file_name = "ssml_output.mp3"
    # file_name = dirname(dirname(abspath(__file__))) + r'\static\audio\outputaudio.mp3'
    file_config = speechsdk.audio.AudioOutputConfig(filename=file_name)
    speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=file_config)
    
    ssml_text = ""
    # ssml_path = os.path.abspath(os.path.join(os.getcwd() , r"polls\AzureVoice\test.xml"))
    ssml_path = dirname(abspath(__file__)) + r"\test.xml"
    with open(ssml_path, 'r', encoding='UTF-8') as f:
        ssml_text = f.read()
    result = speech_synthesizer.speak_ssml_async(ssml_text).get()

    # Check result
    if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
        print("the audio was saved to [{}]".format(file_name))
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print("Speech synthesis canceled: {}".format(cancellation_details.reason))
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print("Error details: {}".format(cancellation_details.error_details))



if __name__ == "__main__":
    text_to_mp3("这是参数文本合成示例")
    text_to_mp3_ssml()
    # text_to_mp3_ssml()